<template>
  <div class="app-container">
    <span style="position: relative; float: right; border:1px">
      <el-button type="primary" icon="el-icon-plus" @click="addDialog" > 新建脚本任务 </el-button>
    </span>
    <ScriptTask ref="addScript" :title="addTitle" operate="add"  @fetchScriptData="fetchScriptData"></ScriptTask>
    <br />
    <br />
    <br />
    <el-table
      ref="scriptTable"
      v-loading="listLoading"
      :data="scriptList"
      element-loading-text="Loading"
      border
      fit
      stripe
      resizable
      highlight-current-row
      :row-key="getRowKey"
      @row-click="handleRowClick"
      :expand-row-keys="expands"
      @expand-change="expandChange"
    >
      <el-table-column type="expand">
        <template slot-scope="scope_item">
          <el-table
            :data="buildList"
            fit
            style="width: 100%">
            <el-table-column
              label="脚本ID"
              width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.scriptId }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="上次构建"
              width="300">
              <template slot-scope="scope">
                <span style="color: #409EFF"
                      v-if="scope.row.lastBuild.url !== undefined && scope.row.lastBuild.url.length >= 1" >
                  <a :href="scope.row.lastBuild.url" target="_blank">{{scope.row.lastBuild.number}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="上次成功构建"
              width="300">
              <template slot-scope="scope">
                <span style="color: #409EFF"
                      v-if="scope.row.lastSuccessfulBuild.url !== undefined && scope.row.lastSuccessfulBuild.url.length >= 1" >
                  <a :href="scope.row.lastSuccessfulBuild.url" target="_blank">{{scope.row.lastSuccessfulBuild.number}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="上次失败构建"
              width="300">
              <template slot-scope="scope">
                <span style="color: #409EFF"
                      v-if="scope.row.lastFailedBuild.url !== undefined && scope.row.lastFailedBuild.url.length >= 1" >
                  <a :href="scope.row.lastFailedBuild.url" target="_blank">{{scope.row.lastFailedBuild.number}}</a>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="60" prop="id">
        <template slot-scope="scope">
          {{ scope.row.scriptId }}
        </template>
      </el-table-column>
      <el-table-column label="脚本名称" width="150" prop="scriptName">
        <template slot-scope="scope">
          <span style="color: #409EFF"
                v-if="scope.row.jobFullUrl !== undefined && scope.row.jobFullUrl !== null && scope.row.jobFullUrl !== ''">
            <a :href="scope.row.jobFullUrl" target="_blank">{{ scope.row.scriptName }}</a>
          </span>
          <span v-else>
            {{ scope.row.scriptName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="代码仓库" width="350" align="center" prop="codeRepository">
        <template slot-scope="scope">
          <span>{{ scope.row.codeRepository }}</span>
        </template>
      </el-table-column>
      <el-table-column label="脚本描述" width="150" align="center" prop="description">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="所属项目/产品" width="120" align="center" prop="product">
        <template slot-scope="scope">
          {{ scope.row.product }}
        </template>
      </el-table-column>
      <el-table-column label="功能模块" width="120" align="center" prop="module">
        <template slot-scope="scope">
          {{ scope.row.module }}
        </template>
      </el-table-column>
      <el-table-column label="执行状态" width="90" align="center" prop="lastBuildStatus">
        <template slot-scope="scope">
          {{ scope.row.lastBuildStatus }}
        </template>
      </el-table-column>
      <el-table-column label="执行时间" width="170" align="center" prop="lastBuildTime">
        <template slot-scope="scope">
          {{ scope.row.lastBuildTime }}
        </template>
      </el-table-column>
      <el-table-column label="耗时（秒）" width="100" align="center" prop="lastBuildTime">
        <template slot-scope="scope">
          {{ scope.row.duration }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200">
        <template slot-scope="scope">
          <el-row :gutter="5">
            <el-col :span="40">
              <span>
                <el-tooltip content="编辑" placement="top" :hide-after="800">
                  <el-button
                    size="mini" class="operate-button"
                    @click="editDialog(scope.$index, scope.row)">
                    <i class="el-icon-edit el-icon--right" style="color: #409EFF;"></i>
                  </el-button>
                </el-tooltip>
                <ScriptTask ref="editScript" :title="editTitle" operate="edit" @fetchScriptData="fetchScriptData"></ScriptTask>
            </span>
            </el-col>
            <el-col :span="40">
              <span>
                <el-tooltip content="开始构建" placement="top" :hide-after="800">
                  <el-button :disabled="scope.row.jobFullUrl === undefined || scope.row.jobFullUrl === null || scope.row.jobFullUrl === ''"
                    size="mini" class="operate-button"
                    @click="confirmBuild(scope.$index, scope.row)">
                    <i class="el-icon-caret-right el-icon--right" style="color: #409EFF;"></i>
                  </el-button>
                </el-tooltip>
                <BuildParams ref="buildDialog" @getBuildList="getBuildList" @fetchScriptData="fetchScriptData"></BuildParams>
              </span>
            </el-col>
            <el-col :span="40">
              <span>
                <el-tooltip content="删除" placement="top" :hide-after="800">
                  <el-button
                    size="mini" class="operate-button"
                    @click="delDialog(scope.$index, scope.row)">
                    <i class="el-icon-delete el-icon--right" style="color: #409EFF;"></i>
                  </el-button>
                </el-tooltip>
              </span>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {delScript, getScripts} from '@/api/script'
import {getBuild} from '@/api/build'
import ScriptTask from "@/components/script/ScriptTask";
import BuildParams from "@/components/script/BuildParams";

export default {
  components: {ScriptTask, BuildParams},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      addTitle: "新建脚本",
      editTitle: "编辑脚本",
      scriptList: [],
      buildList: [],
      listLoading: true,
      scriptId: '',
      expands: [],
      getRowKey(row) {
        return row.scriptId
      }
    }
  },
  created() {
    this.$nextTick(() =>{
      this.fetchScriptData()
    })
  },
  methods: {
    fetchScriptData() {
      this.listLoading = true
      getScripts().then(res => {
        this.scriptList = res.data
        this.listLoading = false
      })
    },
    async handleRowClick (row, index, e) {
      if (index.label !== '操作' && index.label !== '脚本名称') {
        this.$refs.scriptTable.toggleRowExpansion(row)
      }
    },
    async expandChange(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = []
        if (row) {
          this.scriptId = row.scriptId
          this.getBuildList(Number(this.scriptId))
          this.expands.push(row.scriptId)//只展开当前行id

        } else {
          this.expands = []
        }
      }
    },
    getBuildList: function (scriptId) {
      let params = {
        scriptId : scriptId
      }
      getBuild(params).then(res => {
        if (res.code === 200 && res.data) {
            this.buildList = res.data.map(item => {
              item.lastBuild = JSON.parse(item.lastBuild)
              item.lastFailedBuild = JSON.parse(item.lastFailedBuild)
              item.lastSuccessfulBuild = JSON.parse(item.lastSuccessfulBuild)
              return item
            })
        } else {
          this.buildList = []
        }
      })
    },
    addDialog() {
      this.$refs.addScript.showDialog()
    },
    editDialog(index, row) {
      this.$refs.editScript.showDialog(index, row)
    },
    delDialog(index, row) {
      let script_name = row.scriptName
      let params = {
        id: row.scriptId
      }
      this.$confirm('当前正在删除 '+ script_name+' 的脚本', '确认删除吗', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        delScript(params).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchScriptData()
          } else {
            this.$message({
              type: 'error',
              message: '删除异常!'
            });
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '接口调用异常!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    confirmBuild: function (index, row) {
      console.log('index, row: ', index, row)
      this.$refs.buildDialog.showDialog(index, row)
    }
  }
}
</script>

<style lang="less" scoped>
.operate-button {
  width: 30px;
  height: 30px;
  padding: 0;
  /deep/ i {
    font-size: 16px;
  }
}
</style>
